function data = PV_ldgh_series(fname,N,k,l,outfile)
% data = PV_ldgh_series(fname,N,k,l,outfile)
%
% Call PV_ldgh for a series of files and prepare a .pvd file to
% collect the generated vtk files.
%
% fname nust contain a '%' to indicate the subdomain.
%
% Moreover, the collected and/or postprocessed data are collected in
% the output argument data.

 part_format = '%.3i';

 % Summary file
 fnameNX = [outfile,'-lambda.pvd'];
 fid1 = fopen(fnameNX,'w');
 fnameNX = [outfile,'-uomega.pvd'];
 fid2 = fopen(fnameNX,'w');
 
 line = '<?xml version="1.0"?>';
 fprintf(fid1,'%s\n',line);
 fprintf(fid2,'%s\n',line);
 line = '<VTKFile type="Collection" version="0.1" byte_order="BigEndian">';
 fprintf(fid1,'%s\n',line);
 fprintf(fid2,'%s\n',line);
 line = ' <Collection>';
 fprintf(fid1,'%s\n',line);
 fprintf(fid2,'%s\n',line);

 % Part loop
 Npos = find(fname=='%');
 for i=0:N
   if(N==0)
     fnameN = [fname(1:Npos-1),                       fname(Npos+1:end)];
   else
     fnameN = [fname(1:Npos-1),num2str(i,part_format),fname(Npos+1:end)];
   end
   Xpos = find(fnameN=='$');
   fnameNX = [fnameN(1:Xpos-1),'grid',fnameN(Xpos+1:end)];
   grid = load(fnameNX);
   fnameNX = [fnameN(1:Xpos-1),'base',fnameN(Xpos+1:end)];
   base = load(fnameNX);
   fnameNX = [fnameN(1:Xpos-1),'results', ...
              fnameN(Xpos+1:end)];
   res = load(fnameNX);

   fnameNX = [outfile,'-',num2str(i,part_format),'.vtu'];
   PV_ldgh(grid.grid,base.base,res.lam,res.uuu,res.qqq,
	   k,l,fnameNX,res.test_name)

   line = ['  <DataSet timestep="', num2str(1), ...
           '" group="" part="', num2str(i,'%i'), ...
           '" file="',fnameNX(1:end-4),'-lambda.vtu"/>'];
   fprintf(fid1,'%s\n',line);
   line = ['  <DataSet timestep="', num2str(1), ...
           '" group="" part="', num2str(i,'%i'), ...
           '" file="',fnameNX(1:end-4),'-uomega.vtu"/>'];
   fprintf(fid2,'%s\n',line);

   if(nargout>0) % collect data
     data.grid{i+1}     = grid.grid;
     data.ddc_grid{i+1} = grid.ddc_grid;
     data.base{i+1}     = base.base;
     data.lam{i+1}      = res.lam;
   end
 end

 line = ' </Collection>';
 fprintf(fid1,'%s\n',line);
 fprintf(fid2,'%s\n',line);
 line = '</VTKFile>';
 fprintf(fid1,'%s\n',line);
 fprintf(fid2,'%s\n',line);

 fclose(fid1);
 fclose(fid2);

return

